package api

import (
	"crypto/tls"
	"encoding/json"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"io/ioutil"
	"micro-grpc-server/app/http/controllers"
	"net/http"
)

type DocController struct {
	controllers.Controller
}

func (c *DocController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("GET", "/", "View")
	b.Handle("GET", "/json", "Json")
}

func (c *DocController) View(ctx iris.Context) {
	// 忽略证书校验
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}
	client := &http.Client{Transport: tr}
	res, err := client.Get("https://doc.muggle-dev.com")

	if err != nil {
		_, _ = ctx.JSON("load error " + err.Error())
		return
	}
	html, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	_, _ = ctx.WriteString(string(html))
}

func (c *DocController) Json(ctx iris.Context) {
	bytes, err := ioutil.ReadFile("docs/swagger.json")
	if err != nil {
		ctx.Application().Logger().Debugf(err.Error())
		return
	}
	var doc interface{}
	err = json.Unmarshal(bytes, &doc)
	_, _ = ctx.JSON(doc)
}
